#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main()
{
  int fds[2];
  if(pipe(fds) < 0){
    perror("pipe");
    return 1;
  }

  pid_t fd = fork();
  if(fd < 0){
    perror("fork");
  }
  else if(fd == 0){
    //child
    close(fds[0]);
  //  int count = 5;
   // const char* msg = ".";
    const char* msg = "child# Hello father process!";
    while(1){
      write(fds[1], msg, strlen(msg));
      sleep(1);
      //sleep(1000);
      //printf("%d\n", count);
      //count++;
  //    count--;
    }
  }
  
  close(fds[1]);
  char* msg[128];
  while(1){
    //sleep(1000000);
    msg[0] = 0;
    ssize_t s = read(fds[0], msg, sizeof(msg) - 1);
    if(s < 0){
      perror("read");
      break;
    }
    else if(s == 0){
      //写入结束
      printf("read file end\n");
      break;
    }
    else{
      msg[s] = 0;
      printf("%s\n", msg);
      sleep(3);
      close(fds[0]);
    }
  }

  int status = 0;
  waitpid(fd, &status, 0);
  if(WIFEXITED(status))
  printf("exit code: %d  sighal: %d\n", WEXITSTATUS(status), WTERMSIG(status));
    else
  printf("exit code: %d  sighal: %d\n", WEXITSTATUS(status), WTERMSIG(status));
      printf("child quit......\n");
  return 0;
}
